<?php


/** ensure this file is being included by a parent file */
defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' );

$_MAMBOTS->registerFunction( 'onAfterSaveSuccess', 'plgHelpDeskEmails_onAfterSaveSuccess' );
$_MAMBOTS->registerFunction( 'onAfterAddCommentSuccess', 'plgHelpDeskEmails_onAfterAddCommentSuccess' );
$_MAMBOTS->registerFunction( 'onAfterAddFileSuccess', 'plgHelpDeskEmails_onAfterAddFileSuccess' );

	/**
	 * Executes the plugin
	 * @return 
	 */
	function plgHelpDeskEmails_onAfterSaveSuccess( $data, $user, &$msg ) 
	{
		$return = plgHelpDeskEmails::onAfterSaveSuccess( $data, $user, $msg );
		return $return;
	}
	/**
	 * Executes the plugin
	 * @return 
	 */
	function plgHelpDeskEmails_onAfterAddCommentSuccess( $data, $user, &$msg ) 
	{
		$return = plgHelpDeskEmails::onAfterAddCommentSuccess( $data, $user, $msg );
		return $return;
	}
	/**
	 * Executes the plugin
	 * @return 
	 */
	function plgHelpDeskEmails_onAfterAddFileSuccess( $data, $user, &$msg ) 
	{
		$return = plgHelpDeskEmails::onAfterAddFileSuccess( $data, $user, $msg );
		return $return;
	}
	
	
	class plgHelpDeskEmails 
	{
		/**
		 * Method is called
		 * after a new message is saved
		 * 
		 * @return 
		 * @param $data Object
		 * @param $user Object
		 * @param $msg Object $msg->type and $msg->message are available
		 */
		function onAfterSaveSuccess( $data, $user, &$msg ) 
		{
			$success = false;
			
			// TODO Update the sendEmailNotices function, or put it all in this plugin?		
			
			//	email users involved
				$data->comment = $data->description;
				$send = plgHelpDeskEmails::sendEmailNotices( $data, $user, 'new' ); 
			
			if ($send) {
				// save success
				$msg->type = 'message';			
				$msg->message .= " - ".HelpDeskText::_( 'Email Sent' );
			} else {
				// save but no email
				$msg->type = 'notice';
				$msg->message .= " - ".HelpDeskText::_( 'Email Failed' );
			}
			
			return $success;		
		}
	
		/**
		 * Method is called
		 * after a new comment is added
		 * 
		 * @return 
		 * @param $data Object
		 * @param $user Object
		 * @param $msg Object $msg->type and $msg->message are available
		 */
		function onAfterAddCommentSuccess( $data, $user, &$msg ) 
		{
			$success = false;
			
			//	email users involved
				$send = plgHelpDeskEmails::sendEmailNotices( $data, $user, 'addcomment' );
	
			if ($send) {
				// save success
				$msg->type = 'message';			
				$msg->message .= " - ".HelpDeskText::_( 'Email Sent' );
			} else {
				// save but no email
				$msg->type = 'notice';
				$msg->message .= " - ".HelpDeskText::_( 'Email Failed' );
			}
			
			return $success;		
		}
	
		/**
		 * Method is called
		 * after a new file is added
		 * 
		 * @return 
		 * @param $data Object
		 * @param $user Object
		 * @param $msg Object $msg->type and $msg->message are available
		 */
		function onAfterAddFileSuccess( $data, $user, &$msg ) 
		{
			$success = false;
			
			//	email users involved
				$send = plgHelpDeskEmails::sendEmailNotices( $data, $user, 'addfile' );
	
			if ($send) {
				// save success
				$msg->type = 'message';			
				$msg->message .= " - ".HelpDeskText::_( 'Email Sent' );
			} else {
				// save but no email
				$msg->type = 'notice';
				$msg->message .= " - ".HelpDeskText::_( 'Email Failed' );
			}
			
			return $success;		
		}	
	
		/**
		 * Returns an array of user objects
		 * 
		 * @param $data Object
		 * @return array
		 */
		function &getEmailRecipients( $data ) {
			$user 		= HelpDeskConfig::getUser();
			$recipients = HelpDeskHelperHelpDesk::getCategoryManagers( $data->categoryid );
					
			if (isset($data->sender_userid)) {
				$sender = HelpDeskConfig::getUser( (int) $data->sender_userid );
				$recipients[] = $sender;
			}
			
			// don't send email to person writing the new comment
			$return = array();
			for ($i=0; $i<count($recipients); $i++) {
				$r = $recipients[$i];
				if ($r->id != $user->id) {
					$return[] = $r;
				}
			}
			
			return $return;
		}
	
		/**
		 * Returns 
		 * 
		 * @param object
		 * @param mixed Boolean
		 * @param mixed Boolean
		 * @return array
		 */
		function &getEmailContent( $data, $user, $type ) 
		{
			$mainframe 	= HelpDeskConfig::getApplication();
			$type = strtolower($type);
			
			$return = array();
			$link = HelpDeskUrl::root()."index.php?option=com_helpdesk&controller=ticket&task=view&id=".$data->id;
			$link = HelpDeskRoute::_( $link, false );
			
			$return = new stdClass();
			$return->body = '';
			$return->subject = '';
	
			// get config settings
			$config = &HelpDeskConfig::getInstance();
			// TODO Move these to parameters for the plugin
			$emails_includedescription 		= $config->get( 'emails_includedescription', '0' );
			$emails_descriptionmaxlength 	= $config->get( 'emails_descriptionmaxlength', '-1' );
			$emails_includecomments 		= $config->get( 'emails_includecomments', '0' );
			$emails_commentmaxlength		= $config->get( 'emails_commentmaxlength', '-1' );		
			$sitename 						= $config->get( 'sitename', $mainframe->getCfg('sitename') );
			$siteurl 						= $config->get( 'siteurl', HelpDeskUrl::root() );
									
			switch ($type) {
				case "3": // addfile
				case "addfile":			
					$return->subject =  sprintf( HelpDeskText::_( 'New Attachment Email Subject' ), $user->name );
					$return->body = sprintf( HelpDeskText::_( 'New Attachment Email Body' ), $user->name, $sitename, $link);
				  break;
				case "2": // addcomment
				case "addcomment":
				case "comment":
					$return->subject =  sprintf( HelpDeskText::_( 'New Comment Email Subject' ), $user->name );
					if ($emails_includecomments) {
						// if include, trim and set body
						if ($emails_commentmaxlength > 0) {
							$text = substr( stripslashes( $data->comment ), 0, $emails_commentmaxlength );
							$text .= ' 
	-- 
	';
							$text .= sprintf( HelpDeskText::_( 'New Comment Email Body' ), $user->name, $sitename, $link);
						} else {
							$text = stripslashes( $data->comment );
							$text .= ' 
	-- 
	';
							$text .= sprintf( HelpDeskText::_( 'New Comment Email Body' ), $user->name, $sitename, $link);
						}
						$return->body = $text;
					} else {
						// else 
						$return->body = sprintf( HelpDeskText::_( 'New Comment Email Body' ), $user->name, $sitename, $link);
					}
				  break;
				case "1": // new
				default:
					$return->subject =  sprintf( HelpDeskText::_( 'New Ticket Email Subject' ), $user->name );
					
					if ($emails_includedescription) {
						// if include, trim and set body
						if ($emails_descriptionmaxlength > 0) {
							$text = substr( stripslashes( $data->comment ), 0, $emails_descriptionmaxlength );
							$text .= ' 
	-- 
	';
							$text .= sprintf( HelpDeskText::_( 'New Ticket Email Body' ), $user->name, $sitename, $link);
						} else {
							$text = stripslashes( $data->comment );
							$text .= ' 
	-- 
	';
							$text .= sprintf( HelpDeskText::_( 'New Ticket Email Body' ), $user->name, $sitename, $link);
						}
						$return->body = $text;
					} else {
						// else 
						$return->body = sprintf( HelpDeskText::_( 'New Ticket Email Body' ), $user->name, $sitename, $link);
					}
				  break;
			}
			
			return $return;
	
		}
	
		/**
		 * Returns 
		 * @param mixed Boolean
		 * @param array Email content
		 * @return boolean
		 */
		function &sendEmailNotices( $data, $user, $type='1' ) 
		{
			$mainframe 	= HelpDeskConfig::getApplication();
			$success 	= false;
			$done 		= array();
					
			// grab config settings for sender name and email
			$config 	= HelpDeskConfig::getInstance();
			$mailfrom 	= $config->get( 'emails_defaultemail', $mainframe->getCfg('mailfrom') );
			$fromname 	= $config->get( 'emails_defaultname', $mainframe->getCfg('fromname') );
			$sitename 	= $config->get( 'sitename', $mainframe->getCfg('sitename') );
			$siteurl 	= $config->get( 'siteurl', HelpDeskUrl::root() );
			
			$recipients = plgHelpDeskEmails::getEmailRecipients( $data );
			$content = plgHelpDeskEmails::getEmailContent( $data, $user, $type );
	
			// trigger event onAfterGetEmailContent 
			$dispatcher = HelpDeskHelperPlugin::getInstance(); 
			$dispatcher->trigger('onAfterGetEmailContent', array( $data, &$content) ); 
			
			for ($i=0; $i<count($recipients); $i++) {
				$recipient = $recipients[$i];
				if (!isset($done[$recipient->email])) {
					// Use the internal _sendMail function rather than helper function
					if ( $send = plgHelpDeskEmails::_sendMail( $mailfrom, $fromname, $recipient->email, $content->subject, $content->body ) ) {
						$success = true;
						$done[$recipient->email] = $recipient->email;
					}	
				}
			}		
	
			return $success;
		}
		
		/**
		 * 
		 * @return unknown_type
		 */
		function _sendMail( $from, $fromname, $recipient, $subject, $body, $actions=NULL, $mode=NULL, $cc=NULL, $bcc=NULL, $attachment=NULL, $replyto=NULL, $replytoname=NULL ) 
		{
			$success = false;
			// use this code instead of the HelpDeskHelperEmail
			$message = HelpDeskHelperEmail::getMailer();
			$message->addRecipient( $recipient );
			$message->setSubject( $subject );
			$message->setBody( $body );
			$sender = array( $from, $fromname );
			$message->setSender($sender);
			$sent = $message->send();
			if ($sent == '1') {
				$success = true;
			}
			return $success;
		}
	
	}